package com.tiza.xiaoyoubao.ui.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.tianze.library.base.BaseFragment;
import com.tianze.library.view.SimpleDialog;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.EditInfo;
import com.tiza.xiaoyoubao.entity.TaoBaoAccountInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.entity.bean.JsonBean;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.GetJsonDataUtil;
import com.tiza.xiaoyoubao.utils.ImageLoader;
import com.tiza.xiaoyoubao.utils.ImageUtils;

import org.json.JSONArray;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/**
 * Created by mapple on 17/3/19.
 * 绑定淘宝账号详情
 */

public class TaoBaoBindingDetailFragment extends BaseFragment {

    /**
     * 选择图片的返回码
     */
    public final static int SELECT_IMAGE_RESULT_CODE = 200;
    String[] proj = {MediaStore.MediaColumns.DATA};
    /**
     * 当前选择的图片的路径
     */
    public String mImagePath;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    @BindView(R.id.tv_text)
    TextView tv_text;
    @BindView(R.id.iv_shiMing)
    ImageView iv_shiMing;
    @BindView(R.id.iv_credibility)
    ImageView iv_credibility;
    @BindView(R.id.iv_huaBei)
    ImageView iv_huaBei;
    //账号
    @BindView(R.id.et_taobaoAccount)
    EditText et_taobaoAccount;
    //收货人
    @BindView(R.id.et_consignee)
    EditText et_consignee;
    //收货人手机
    @BindView(R.id.et_consigneePhone)
    EditText et_consigneePhone;
    //城市
    @BindView(R.id.tv_chooseCity)
    TextView tv_chooseCity;
    //地址
    @BindView(R.id.et_address)
    EditText et_address;
    //性别
    @BindView(R.id.tv_gender)
    TextView tv_gender;
    //年龄
    @BindView(R.id.tv_age)
    TextView tv_age;
    //信誉
    @BindView(R.id.tv_credibility)
    TextView tv_credibility;
    @BindView(R.id.btn_save)
    Button btn_save;
    @BindView(R.id.view_shiMing)
    View view_shiMing;
    @BindView(R.id.view_credibility)
    View view_credibility;
    @BindView(R.id.tv_huabei)
    TextView tv_huabei;
    UserInfo mUserInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);
    private TaoBaoAccountInfo mTaoBaoAccountInfo;
    private int i = 0;
    private String account, receiver, recePhone, city, address, sex, age, reputation;
    private File imageFile, image1, image2;
    private File image3=null;
    private Bitmap bitmap1, bitmap2;
    private Bitmap bitmap3=null;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_taobao_detail;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        mTaoBaoAccountInfo = (TaoBaoAccountInfo) args.getSerializable("info");
        if (null == mTaoBaoAccountInfo) {
            toast("详情加载失败");
            finish();
        }
    }

    @Subscriber(tag = Constants.TAG_SET_TAOBAO_SUCCESS)
    private void onEdit(EditInfo info) {
        int type = info.getType();
        switch (type) {
            case EditInfo.TYPE_TAOBAO_GENDER:
                sex = info.getValue();
                tv_gender.setText(sex);
                break;
            case EditInfo.TYPE_TAOBAO_AGE:
                age = info.getValue();
                tv_age.setText(age);
                break;
            case EditInfo.TYPE_TAOBAO_CREDIBILITY:
                reputation = info.getValue();
                tv_credibility.setText(reputation);
                break;
        }
    }

    @Override
    protected void initData() {
        ImageLoader.getInstance().displayImage(mTaoBaoAccountInfo.getImage1(),iv_shiMing);
//        Picasso.with(mActivity)
//               .load(mTaoBaoAccountInfo.getImage1())
//               .placeholder(R.mipmap.rwxq_tupian)
//               .error(R.mipmap.rwxq_tupian)
//               .resize(80,80)
//               .into(iv_shiMing);
        ImageLoader.getInstance().displayImage(mTaoBaoAccountInfo.getImage2(),iv_credibility);
//        Picasso.with(mActivity)
//               .load(mTaoBaoAccountInfo.getImage2())
//               .placeholder(R.mipmap.rwxq_tupian)
//               .error(R.mipmap.rwxq_tupian)
//               .resize(80,80)
//               .into(iv_credibility);
        ImageLoader.getInstance().displayImage(mTaoBaoAccountInfo.getImage3(),iv_huaBei);
    }

    @Override
    protected void initView() {
        SpannableString spannableString = new SpannableString(
                mActivity.getString(R.string.text_notice));
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#ff3a33"));
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(Color.parseColor("#ff3a33"));
        spannableString.setSpan(colorSpan, 6, 21, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(colorSpan1, spannableString.length() - 5,
                                spannableString.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        );
        tv_text.setText(spannableString);
        et_taobaoAccount.setText(mTaoBaoAccountInfo.getAccount());
        et_consignee.setText(mTaoBaoAccountInfo.getReceiver());
        et_consigneePhone.setText(mTaoBaoAccountInfo.getRecephone());
        tv_chooseCity.setText(mTaoBaoAccountInfo.getCity());
        et_address.setText(mTaoBaoAccountInfo.getAddress());
        tv_gender.setText(mTaoBaoAccountInfo.getSex());
        tv_age.setText(mTaoBaoAccountInfo.getAge());
        tv_credibility.setText(mTaoBaoAccountInfo.getReputation());
        if (mTaoBaoAccountInfo.getAuth() == 1) {
            btn_save.setVisibility(View.INVISIBLE);
            et_taobaoAccount.setEnabled(false);
            et_consignee.setEnabled(false);
            et_consigneePhone.setEnabled(false);
            tv_chooseCity.setEnabled(false);
            et_address.setEnabled(false);
            tv_gender.setEnabled(false);
            tv_age.setEnabled(false);
            tv_credibility.setEnabled(false);
            view_shiMing.setEnabled(false);
            view_credibility.setEnabled(false);
        } else if (mTaoBaoAccountInfo.getAuth() == 0) {
            btn_save.setText("取消审核");
        }
        if (mTaoBaoAccountInfo.getHuabei() == 0) {
            tv_huabei.setText("审核中");
            tv_huabei.setTextColor(getResources().getColor(R.color.red));
        } else if (mTaoBaoAccountInfo.getHuabei() == 1) {
            tv_huabei.setText("审核通过");
            tv_huabei.setTextColor(getResources().getColor(R.color.steel_blue));
        } else if (mTaoBaoAccountInfo.getHuabei() == 2) {
            tv_huabei.setText("审核未通过");
            tv_huabei.setTextColor(getResources().getColor(R.color.red));
        }
    }


    private String checkMessage() {
        account = et_taobaoAccount.getText().toString().trim();
        if (TextUtils.isEmpty(account)) return "请输入淘宝账号";
        receiver = et_consignee.getText().toString().trim();
        if (TextUtils.isEmpty(receiver)) return "请输入收货人姓名";
        recePhone = et_consigneePhone.getText().toString().trim();
        if (TextUtils.isEmpty(recePhone)) return "请输入收货人手机号";
        city = tv_chooseCity.getText().toString().trim();
        if (city.equals("选择城市")) return "请选择城市";
        address = et_address.getText().toString().trim();
        if (TextUtils.isEmpty(address)) return "请输入收货地址";
        sex = tv_gender.getText().toString().trim();
        if (sex.equals("性别")) return "请选择性别";
        age = tv_age.getText().toString().trim();
        if (age.equals("年龄")) return "请选择年龄";
        reputation = tv_credibility.getText().toString().trim();
        if (reputation.equals("信誉")) return "请选择荣誉等级";
        if (bitmap1 == null || bitmap2 == null) return "请选择要上传的照片";
        return "";
    }


    @OnClick({
            R.id.view_credibility,
            R.id.view_shiMing,
            R.id.view_huaBei,
            R.id.tv_chooseCity,
            R.id.tv_gender,
            R.id.tv_credibility,
            R.id.tv_age,
            R.id.btn_save
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_credibility:
                showCustomConfirmDialog("请选择上传方式", "手机相册", "手机拍照",
                                        new SimpleDialog.OnSimpleClickListener() {
                                            @Override
                                            public void onClick(SimpleDialog simpleDialog) {
                                                Intent intent = new Intent(
                                                        Intent.ACTION_GET_CONTENT);
                                                i = 1;
                                                pickPhoto();
                                                simpleDialog.dismiss();
                                            }
                                        }, new SimpleDialog.OnSimpleClickListener() {
                            @Override
                            public void onClick(SimpleDialog simpleDialog) {
                                i = 1;
                                takePhoto();
                                simpleDialog.dismiss();
                            }
                        }
                );
                break;
            case R.id.view_shiMing:
                showCustomConfirmDialog("请选择上传方式", "手机相册", "手机拍照",
                                        new SimpleDialog.OnSimpleClickListener() {
                                            @Override
                                            public void onClick(SimpleDialog simpleDialog) {
                                                Intent intent = new Intent(
                                                        Intent.ACTION_GET_CONTENT);
                                                i = 2;
                                                pickPhoto();
                                                simpleDialog.dismiss();
                                            }
                                        }, new SimpleDialog.OnSimpleClickListener() {
                            @Override
                            public void onClick(SimpleDialog simpleDialog) {
                                i = 2;
                                takePhoto();
                                simpleDialog.dismiss();
                            }
                        }
                );
                break;
            case R.id.view_huaBei:
                showCustomConfirmDialog("请选择上传方式", "手机相册", "手机拍照",
                                        new SimpleDialog.OnSimpleClickListener() {
                                            @Override
                                            public void onClick(SimpleDialog simpleDialog) {
                                                Intent intent = new Intent(
                                                        Intent.ACTION_GET_CONTENT);
                                                i = 3;
                                                pickPhoto();
                                                simpleDialog.dismiss();
                                            }
                                        }, new SimpleDialog.OnSimpleClickListener() {
                            @Override
                            public void onClick(SimpleDialog simpleDialog) {
                                i = 3;
                                takePhoto();
                                simpleDialog.dismiss();
                            }
                        }
                );
                break;
            case R.id.tv_chooseCity:
                initJsonData();
                break;
            case R.id.tv_gender:
                UIHelper.showChooseGerder(mActivity);
                break;
            case R.id.tv_credibility:
                UIHelper.showCredibility(mActivity);
                break;
            case R.id.tv_age:
                UIHelper.showChooseAge(mActivity);
                break;
            case R.id.btn_save:
                if (mTaoBaoAccountInfo.getAuth() == 0) {
                    showCustomConfirmDialog("确定要取消账号审核吗?", "否", "是",
                                            new SimpleDialog.OnSimpleClickListener() {
                                                @Override
                                                public void onClick(SimpleDialog simpleDialog) {
                                                    simpleDialog.dismiss();
                                                }
                                            }, new SimpleDialog.OnSimpleClickListener() {
                                @Override
                                public void onClick(SimpleDialog simpleDialog) {
                                    deleteTaoBaoInfo();
                                    simpleDialog.dismiss();
                                }
                            }
                    );
                } else if (mTaoBaoAccountInfo.getAuth() == 2) {
                    String message = checkMessage();
                    if (!TextUtils.isEmpty(message)) {
                        toast(message);
                        return;
                    }
                   setBuyerTaobao();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMAGE_RESULT_CODE && resultCode == RESULT_OK) {
            String imagePath = "";
            Uri uri = null;
            if (data != null && data.getData() != null) {// 有数据返回直接使用返回的图片地址
                uri = data.getData();
                Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null,
                                                                         null
                );
                if (cursor == null) {
                    uri = ImageUtils.getUri(getActivity(), data);
                }
                imagePath = ImageUtils.getFilePathByFileUri(getActivity(), uri);
            } else {// 无数据使用指定的图片路径
                imagePath = mImagePath;
                int i = ImageUtils.parseImageDegree(imagePath);
                System.out.println("旋转的角度:" + i);

            }
            //获取图片缩略图，避免OOM
            Bitmap bitmap = ImageUtils.getImageThumbnail(imagePath, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5);
            if (i == 1) {
                image1 = new File(imagePath);
                bitmap1 = ImageUtils.rotateBitmap(bitmap, ImageUtils.parseImageDegree(imagePath));
                iv_credibility.setImageBitmap(bitmap1);
            } else if (i == 2) {
                image2 = new File(imagePath);
                bitmap2 = ImageUtils.rotateBitmap(bitmap, ImageUtils.parseImageDegree(imagePath));
                iv_shiMing.setImageBitmap(bitmap2);
            }else if (i == 3) {
                image3 = new File(imagePath);
                bitmap3 = ImageUtils.rotateBitmap(bitmap, ImageUtils.parseImageDegree(imagePath));
                iv_shiMing.setImageBitmap(bitmap3);
            }

        }
    }

    /***
     * 从相册中取图片
     */
    public void pickPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        getActivity().startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
    }

    /**
     * 拍照获取图片
     */
    public void takePhoto() {
        // 执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            /**
             * 通过指定图片存储路径，解决部分机型onActivityResult回调 data返回为null的情况
             */
            //获取与应用相关联的路径
            String imageFilePath = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                                                .getAbsolutePath();
            if (i == 1) {
                String imagePath1 = "/" + "credibility.jpg";
                image1 = new File(imageFilePath, imagePath1);// 通过路径创建保存文件
                if (image1.exists()) {
                    image1.delete();
                    image1 = new File(imageFilePath, imagePath1);
                }
                imageFile = image1;
            } else if (i == 2) {
                String imagePath2 = "/" + "certification.jpg";
                image2 = new File(imageFilePath, imagePath2);// 通过路径创建保存文件
                if (image2.exists()) {
                    image2.delete();
                    image2 = new File(imageFilePath, imagePath2);
                }
                imageFile = image2;
            }else if (i == 3) {
                String imagePath3 = "/" + "huabei.jpg";
                image3 = new File(imageFilePath, imagePath3);// 通过路径创建保存文件
                if (image3.exists()) {
                    image3.delete();
                    image3 = new File(imageFilePath, imagePath3);
                }
                imageFile = image3;
            }
            mImagePath = imageFile.getAbsolutePath();
            Uri imageFileUri = Uri.fromFile(imageFile);// 获取文件的Uri
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);// 告诉相机拍摄完毕输出图片到指定的Uri
            getActivity().startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
        } else {
            toast("内存卡不存在");
        }
    }

    private void setBuyerTaobao() {
        ApiHttpClient.setBuyerTaoBao(this,String.valueOf(mTaoBaoAccountInfo.getId()), mUserInfo.getWebzzCmsBuyerInfo().getUserid(), account,
                                     receiver, recePhone, city, address, sex, age, reputation,
                                     image1, image2,image3,new JsonCallback<String>(String.class,
                                                                                true) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("网络异常，请检查后再试");
                    }

                    @Override
                    public void onResponse(ResponseInfo<String> response) {
                        int code = response.getCode();
                        if (code == 1) {
                            showWarnDialog(response.getMessage());
                            return;
                        }
                        toast("账号绑定成功");
                        // 通知绑定信息成功
                        EventBus.getDefault().post(true, Constants.TAG_SET_BUYERTAOBAO_SUCCESS);
                        finish();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }
                }
        );
    }

    private void initJsonData() {//解析数据

        String JsonData = new GetJsonDataUtil().getJson(mActivity,
                                                        "province.json"
        );//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null || jsonBean.get(i)
                                                                                      .getCityList()
                                                                                      .get(c)
                                                                                      .getArea()
                                                                                      .size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i)
                                                .getCityList()
                                                .get(c)
                                                .getArea()
                                                .size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void ShowPickerView() {// 弹出选择器


        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity,
                                                                    new OptionsPickerView.OnOptionsSelectListener() {
                                                                        @Override
                                                                        public void onOptionsSelect(
                                                                                int options1,
                                                                                int options2,
                                                                                int options3, View v
                                                                        ) {
                                                                            //返回的分别是三个级别的选中位置
                                                                            String tx = options1Items
                                                                                    .get(options1)
                                                                                    .getPickerViewText() +
                                                                                    options2Items.get(
                                                                                            options1)
                                                                                                 .get(options2) +
                                                                                    options3Items.get(
                                                                                            options1)
                                                                                                 .get(options2)
                                                                                                 .get(options3);
                                                                            tv_chooseCity.setText(
                                                                                    tx);
                                                                        }
                                                                    }
        )

                .setTitleText("城市选择").setDividerColor(Color.BLACK).setTextColorCenter(
                        Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).setOutSideCancelable(false)// default is true
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_SUCCESS:
                    ShowPickerView();
                    break;

                case MSG_LOAD_FAILED:
                    toast("获取城市数据失败");
                    break;

            }
        }
    };

    private void deleteTaoBaoInfo() {
        ApiHttpClient.deleteTaoBaoInfo(this, String.valueOf(mTaoBaoAccountInfo.getId()),
                                    new JsonCallback<String>(String.class, true) {

                                        @Override
                                        public void onBefore(Request request) {
                                            super.onBefore(request);
                                        }

                                        @Override
                                        public void onError(Call call, Exception e) {
                                            toast("网络连接失败,请稍后再试");
                                        }

                                        @Override
                                        public void onResponse(ResponseInfo<String> response) {
                                            int code = response.getCode();
                                            String message = response.getMessage();
                                            if (code == 1) {
                                                showWarnDialog(message);
                                                return;
                                            }
                                            // 通知取消淘宝号审核成功
                                            EventBus.getDefault().post(true, Constants.TAG_SET_BUYERTAOBAO_SUCCESS);
                                            finish();
                                        }

                                        @Override
                                        public void onAfter() {
                                            super.onAfter();
                                        }
                                    }
        );
    }

}
